package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"awesomeProject/util"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"

	//"encoding/json"
)

type OrderProcessSrv struct{}

func (r *OrderProcessSrv) Pagination(req request.OrderProcessPagination) response.Resp {
	var orderProcess []model.OrderProcess
	filter := bson.D{}
	if req.OrderSn != "" {
		filter = append(filter, bson.E{Key: "orderSn", Value: req.OrderSn})
	}
	match := bson.D{{"$match", filter}}
	sort := bson.D{{"$sort", bson.M{"processDate": 1, "id": 1, "sort": -1}}}
	cursor, err := global.MongoDB.Collection(model.OrderProcess{}.TableName()).Aggregate(context.TODO(), mongo.Pipeline{match, sort})
	if err = cursor.All(context.TODO(), &orderProcess); err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	if len(orderProcess) == 0 {
		return response.OK.WithData(map[string]interface{}{
			"total": 0,
			"list":  orderProcess,
		})
	}

	count := bson.D{{"$count", "total"}}
	countCursor, err := global.MongoDB.Collection(model.OrderProcess{}.TableName()).Aggregate(context.TODO(), mongo.Pipeline{match, count})
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	var countResult []map[string]interface{}
	if err = countCursor.All(context.TODO(), &countResult); err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}

	return response.OK.WithData(map[string]interface{}{
		"total": countResult[0]["total"],
		"list":  orderProcess,
	})
}

func (r *OrderProcessSrv) Update(req []request.OrderProcessUpdate, operator model.User) response.Resp {
	// global.LoggerOut(len(req))
	if len(req) > 0 {
		var updateIds []uint
		var insertIds []uint
		var oldIds []uint
		var orderProcess []model.OrderProcess

		for _, updateItem := range req {
			//if updateItem.ProcessContent != "" {

				orderProcessUpdate := model.OrderProcess {
					ID: updateItem.ID,
					OrderSn: updateItem.OrderSn,
					OrderID: updateItem.OrderID,
					ShopId: updateItem.ShopId,
					Sort: updateItem.Sort,
				}
				orderProcessUpdate.ProcessDate = updateItem.ProcessDate
				orderProcessUpdate.ProcessContent = updateItem.ProcessContent

				if updateItem.ID > 0 {
					updateIds = append(updateIds, uint(updateItem.ID))
					orderProcessUpdate.CreateUser = updateItem.CreateUser
					orderProcessUpdate.CreateAt = updateItem.CreateAt
					orderProcessUpdate.UpdateUser = updateItem.UpdateUser
					orderProcessUpdate.UpdateAt = updateItem.UpdateAt

					oneOrderProcess := model.OrderProcessFillAble {}
					filterOne := bson.D{bson.E{Key: "orderSn", Value: updateItem.OrderSn}}
					filterOne = append(filterOne, bson.E{Key: "id", Value: bson.M{"$eq": updateItem.ID}})
					errOne := global.MongoDB.Collection(model.OrderProcess{}.TableName()).FindOne(context.TODO(), filterOne).Decode(&oneOrderProcess)
					if errOne != nil {
						return response.ErrUpdate.SetMsg(errOne.Error())
					}
					if(orderProcessUpdate.UpdateAt.IsZero() || oneOrderProcess.ProcessDate != orderProcessUpdate.ProcessDate ||
						oneOrderProcess.ProcessContent != orderProcessUpdate.ProcessContent) {
						orderProcessUpdate.UpdateUser = operator.Username
						orderProcessUpdate.UpdateAt = time.Now()
					}

					filter := bson.D{bson.E{Key: "orderSn", Value: updateItem.OrderSn}}
					filter = append(filter, bson.E{Key: "id", Value: bson.M{"$eq": updateItem.ID}})
					update := bson.D{{"$set", orderProcessUpdate}}
					opts := options.Update().SetUpsert(true)  //如果匹配不存在，则插入

					_, err := global.MongoDB.Collection(model.OrderProcess{}.TableName()).UpdateOne(context.TODO(), filter, update, opts)
					if err != nil {
						return response.ErrUpdate.SetMsg(err.Error())
					}
				} else {
					orderProcessUpdate.CreateUser = operator.Username
					orderProcessUpdate.CreateAt = time.Now()
					orderProcessUpdate.UpdateUser = operator.Username
					orderProcessUpdate.UpdateAt = time.Now()

					orderProcessUpdate.ID = util.GetTableDataID(model.OrderProcess{}.TableName())
					// global.LoggerOut(orderProcessUpdate.ID)
					insertIds = append(insertIds, uint(orderProcessUpdate.ID))

					res, err := global.MongoDB.Collection(model.OrderProcess{}.TableName()).InsertOne(context.TODO(), orderProcessUpdate)

					//global.LoggerOut(res)
					//global.LoggerOut(err)
					if err != nil {
						return response.ErrStore.SetMsg(err.Error())
					}
					InsertedID := res.InsertedID
					global.LoggerOut(InsertedID)

				}

			//}
		}

		var orderSn = req[0].OrderSn
		if orderSn != "" {
			filter := bson.D{bson.E{Key: "orderSn", Value: orderSn}}
			match := bson.D{{"$match", filter}}
			sort := bson.D{{"$sort", bson.M{"id": 1}}}
			cursor, err := global.MongoDB.Collection(model.OrderProcess{}.TableName()).Aggregate(context.TODO(), mongo.Pipeline{match, sort})
			if err = cursor.All(context.TODO(), &orderProcess); err != nil {
				return response.ErrQuery.SetMsg(err.Error())
			}
			if len(orderProcess) > 0 {
				for _, op := range orderProcess {
					if(util.IsExistsUint(insertIds, uint(op.ID))) {
						continue
					}
					oldIds = append(oldIds, op.ID)
				}
			}
		}
		diffIds := util.DiffUintArray(oldIds, updateIds)
		//global.LoggerOut(oldIds)
		//global.LoggerOut(updateIds)
		//global.LoggerOut(diffIds)

		// 不在数据库旧数据中id的则表示删除
		if len(diffIds) > 0 {
			filter := bson.D{bson.E{Key: "orderSn", Value: orderSn}}
			filter = append(filter, bson.E{Key: "id", Value: bson.M{"$in": diffIds}})
			_, err := global.MongoDB.Collection(model.OrderProcess{}.TableName()).DeleteMany(context.TODO(), filter)

			//global.LoggerOut(orderSn)
			//global.LoggerOut(diffIds)

			if err != nil {
				return response.ErrStore.SetMsg(err.Error())
			}
		}

	}

	return response.OK
}
